﻿using System;

namespace ControleRepresentante.Data.Helpers
{
    internal class TableHelper
    {
        private readonly string m_TableName;
        private readonly IDataAccess m_DataAccess;

        public TableHelper(string tableName, IDataAccess dataAccess)
        {
            m_TableName = tableName;
            m_DataAccess = dataAccess;
        }

        public TableHelper AddColumn(string columnName, ColumnType columnType, bool allowNulls, bool isUnique)
        {
            string command = String.Format(@"
                ALTER TABLE {0}
                ADD {1} {2}",
                m_TableName, 
                columnName,
                m_DataAccess.GetTypeName(columnType));

            if (!allowNulls)
            {
                command += " NOT NULL";
            }
            if (isUnique)
            {
                command += " UNIQUE";
            }

            m_DataAccess.ExecuteCommand(command);
            return this;
        }

        public TableHelper AddForeignKey(string columnName, string foreignTable, string foreignColumnName = "Id")
        {
            m_DataAccess.ExecuteCommand(String.Format(@"
                ALTER TABLE {0}
                ADD FOREIGN KEY ({1})
                REFERENCES {2}({3})",
                m_TableName,
                columnName,
                foreignTable,
                foreignColumnName));
            return this;
        }

        public TableHelper DropForeignKey(string foreignKeyConstraint)
        {
            m_DataAccess.ExecuteCommand(String.Format(@"
                ALTER TABLE {0}
                DROP FOREIGN KEY {1}",
                m_TableName,
                foreignKeyConstraint));
            return this;
        }

        public TableHelper DropColumn(string columnName)
        {
            m_DataAccess.ExecuteCommand(String.Format(@"
                ALTER TABLE {0}
                DROP COLUMN {1}",
                m_TableName,
                columnName));
            return this;
        }

        public void RenameColumn(string currentName, string newName, ColumnType columnType)
        {
            m_DataAccess.ExecuteCommand(String.Format(@"
                ALTER TABLE {0}
                CHANGE {1} {2} {3}",
                m_TableName,
                currentName,
                newName,
                m_DataAccess.GetTypeName(columnType)));
        }
    }
}